import { CallHandler, ExecutionContext, HttpException, HttpStatus, Injectable, NestInterceptor } from '@nestjs/common';
import { Response } from 'express';
import { catchError, map, Observable, throwError, timeout } from 'rxjs';

@Injectable()
export class ResponseFormatterInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    return next.handle().pipe(
      /** 全局默认超时时间 */
      timeout(5 * 1000),

      map(data => {
        const http = context.switchToHttp();
        const res = http.getResponse<Response>();
        const code = res.statusCode;

        return {
          success: true,
          code,
          data,
          message: 'success',
        };
      }),

      catchError(error => {
        // 检查是否是 HttpException 类型
        if (error instanceof HttpException) {
          // 如果是 HttpException，则直接返回
          return throwError(() => error);
        }

        // 如果不是 HttpException，返回自定义错误
        return throwError(
          () =>
            new HttpException(
              {
                statusCode: HttpStatus.INTERNAL_SERVER_ERROR,
                message: 'Internal Server Error',
                error: error.message || 'Unknown error occurred',
              },
              HttpStatus.INTERNAL_SERVER_ERROR,
            ),
        );
      }),
    );
  }
}
